package com.hatom.cameraxhelp.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.util.Log;
import android.view.Surface;

import androidx.annotation.NonNull;
import androidx.camera.core.AspectRatio;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.blankj.utilcode.util.ThreadUtils;
import com.google.common.util.concurrent.ListenableFuture;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author tangxianfeng
 * Created on 2022/04/22
 * desc   : CameraX 工具类 一次建立 直接获取预览
 * 目前仅支持预览
 * 考虑内存不自引用 不做单例
 */
public class CameraXHelp {

    private static final String TAG="CameraXHelp";
    private ProcessCameraProvider cameraProvider;
    private Preview previewView;
    private ImageAnalysis imageAnalysis;//预览流分析
    private LifecycleOwner lifecycleOwner;

    private boolean isBackCamera= true;//是否为后置摄像 默认是

    //初始化相机
    @SuppressLint("RestrictedApi")
    public void setUpCamera(LifecycleOwner lifecycleOwner, @NotNull Context context, @NotNull Preview.SurfaceProvider surfaceProvider, @NotNull AnalaysListener analaysListener) {

        ExecutorService cameraExecutor = Executors.newSingleThreadExecutor();
        this.lifecycleOwner=lifecycleOwner;



        imageAnalysis = new ImageAnalysis.Builder()
                .setTargetRotation(Surface.ROTATION_0)//0度旋转
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)//设置宽高比
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)//默认用最新的流图
                .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888) //默认是YUV 420格式
                .build();//图片分析对象


        imageAnalysis.setAnalyzer(cameraExecutor, new ImageAnalysis.Analyzer() {
            @Override
            public void analyze(@NonNull @NotNull ImageProxy imageProxy) {
                new FaceDetectTask(imageProxy,analaysListener).execute();//执行后台现场的识别
            }
        });


        final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(context);
        cameraProviderFuture.addListener(new Runnable() {
            @Override
            public void run() {
                // CameraProvider
                try {
                    cameraProvider = cameraProviderFuture.get();
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
                previewView = new Preview.Builder()
                        .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                        .build();
                previewView.setSurfaceProvider(surfaceProvider);
                cameraProvider.unbindAll();
                Log.e("TEST","isBackCamera :: "+isBackCamera);
                cameraProvider.bindToLifecycle(lifecycleOwner, isBackCamera?CameraSelector.DEFAULT_BACK_CAMERA:CameraSelector.DEFAULT_FRONT_CAMERA, imageAnalysis, previewView);
            }
        }, ContextCompat.getMainExecutor(context));
    }

    //初始化相机
    public void setUpCamera(@NotNull Context context,@NotNull Preview.SurfaceProvider surfaceProvider,@NotNull AnalaysListener analaysListener) {
        if (context instanceof LifecycleOwner){
            Log.e(TAG,"实例类型通过");
        }else {
            analaysListener.error("context not instanceof LifecycleOwner");
            return;
        }
        this.setUpCamera((LifecycleOwner) context,context,surfaceProvider,analaysListener);
    }
    /**
     * 人脸检测Task
     * 封装到后台处理
     */
    private static class FaceDetectTask extends ThreadUtils.SimpleTask<Void> {

        private final ImageProxy imageProxy;
        private final AnalaysListener analaysListener;

        public FaceDetectTask(ImageProxy imageProxy,AnalaysListener analaysListener) {
            this.imageProxy = imageProxy;
            this.analaysListener=analaysListener;
        }

        @Override
        public Void doInBackground() {
            analaysListener.analyze(imageProxy);
            imageProxy.close();
            return null;
        }

        @Override
        public void onSuccess(Void result) {

        }

        public void execute() {
            ThreadUtils.executeByCpu(this);
        }

    }
    //是否为后置摄像头
    public boolean isBackCamera() {
        return isBackCamera;
    }

    public void setBackCamera(boolean backCamera) {

        Log.e("TEST","setBackCamera :: "+backCamera);
        isBackCamera = backCamera;
    }

    //转换摄像头
    public void transCamera(){
        isBackCamera=!isBackCamera;
        cameraProvider.unbindAll();
        CameraSelector cameraSelector=new CameraSelector.Builder()
                .requireLensFacing(isBackCamera?CameraSelector.LENS_FACING_BACK:CameraSelector.LENS_FACING_FRONT)
                .build();
        cameraProvider.bindToLifecycle(lifecycleOwner,cameraSelector, imageAnalysis, previewView);
    }

    public interface AnalaysListener{
        void analyze(@NonNull @NotNull ImageProxy imageProxy);
        void error(String error);
    }

}
